import java.util.concurrent.CompletableFuture;

public class CompletableFutureUtil {
    private static final String sinaCodeUrl = "https://finance.sina.com.cn/code/";
    private static final String neteaseCodeUrl = "https://money.163.com/code/";
    private static final String sinaPriceUrl = "https://finance.sina.com.cn/price/";
    private static final String neteasePriceUrl = "https://money.163.com/price/";

    static void combineQuery() throws InterruptedException {
        CompletableFuture<String> cfQueryFromSina = CompletableFuture.supplyAsync(() -> {
            return queryCode("中国石油", sinaCodeUrl);
        });
        CompletableFuture<String> cfQueryFromNetease = CompletableFuture.supplyAsync(() -> {
           return queryCode("中国石油", neteaseCodeUrl);
        });
        CompletableFuture<Object> cfQuery = CompletableFuture.anyOf(cfQueryFromSina, cfQueryFromNetease);
        CompletableFuture<Double> cfQueryPriceFromSina = cfQuery.thenApplyAsync((code) -> {
            return fetchPrice((String)code, sinaPriceUrl);
        });
        CompletableFuture<Double> cfQueryPriceFrom163 = cfQuery.thenApplyAsync((code) -> {
            return fetchPrice((String)code, neteasePriceUrl);
        });
        CompletableFuture<Object> cfFetch = CompletableFuture.anyOf(cfQueryPriceFromSina, cfQueryPriceFrom163);
        cfFetch.thenAcceptAsync((result) -> {
            System.out.println("price: " + result);
        });
        Thread.sleep(200);
    }

    static String queryCode(String name, String url) {
        System.out.println("query code from url: " + url + "...");
        try {
            Thread.sleep((long)(Math.random() * 1000));
        } catch (Exception _) {

        }
        return "601857";
    }

    static Double fetchPrice(String code, String url) {
        System.out.println("fetch price from url: " + url + "...");
        try {
            Thread.sleep((long)(Math.random() * 100));
        } catch(Exception _) {}
        return 5 + Math.random() * 20;
    }
}
